package com.ruibang.glass.quality.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruibang.glass.quality.domain.req.BatchDetailReq;
import com.ruibang.glass.quality.domain.req.HistoryBatchReq;
import com.ruibang.glass.quality.domain.resp.BatchDetailResp;
import com.ruibang.glass.quality.domain.resp.HistoryBatchResp;
import com.ruibang.glass.quality.domain.resp.ItemLotBindNumResp;
import com.ruibang.glass.quality.mapper.HistoryBatchMapper;
import com.ruibang.glass.quality.service.HistoryBatchService;
import io.seata.common.util.CollectionUtils;
import io.seata.common.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: songJinKang
 * @CreateTime: 2024-04-29  14:30
 * @Description: TODO
 * @Version: 1.0
 */
@Slf4j
@Service
public class HistoryBatchServiceImpl implements HistoryBatchService {

    @Autowired
    private HistoryBatchMapper historyBatchMapper;

    @Override
    public IPage<HistoryBatchResp> pageQuery(HistoryBatchReq historyBatchReq) {
        IPage<HistoryBatchResp> page = historyBatchMapper.pageQuery(new Page<>(historyBatchReq.getPageNo(), historyBatchReq.getPageSize()), historyBatchReq);
        if (page != null && CollectionUtils.isNotEmpty(page.getRecords())) {
            List<String> batchNumbers = page.getRecords().stream().map(HistoryBatchResp::getBatchNumber).collect(Collectors.toList());
            List<ItemLotBindNumResp> itemLotBindNumRespList = historyBatchMapper.getIsBindNumByBatchNumber(batchNumbers);
            if (CollectionUtils.isNotEmpty(itemLotBindNumRespList)) {
                Map<String, Integer> bindNumMap = itemLotBindNumRespList.stream().collect(Collectors.toMap(ItemLotBindNumResp::getBatchNumber, ItemLotBindNumResp::getNum));
                for (HistoryBatchResp historyBatchResp : page.getRecords()) {
                    if (StringUtils.isNotBlank(historyBatchResp.getLevel())) {
                        historyBatchResp.setFinalLevel(historyBatchResp.getLevel());
                    } else {
                        historyBatchResp.setFinalLevel(historyBatchResp.getResult());
                    }
                    historyBatchResp.setMomNum(bindNumMap.get(historyBatchResp.getBatchNumber()));
                }
            }
        }
        return page;
    }

    @Override
    public IPage<BatchDetailResp> getBatchDetail(BatchDetailReq batchDetailReq) {
        return historyBatchMapper.getBatchDetail(new Page<>(batchDetailReq.getPageNo(), batchDetailReq.getPageSize()), batchDetailReq);
    }
}
